
import {Injectable} from '@angular/core'
import {Http,RequestOptions,Headers} from '@angular/http'
import {Observable} from 'rxjs/Rx';
import {User} from './user.model';
import 'rxjs/Rx';
@Injectable()
export class UserServcie{
	//url:string="http://localhost:9000/users"
	url:string="/users"
	constructor(private http:Http){

	}
	findAllUsers():Observable<User[]>{
		return this.http.get(this.url)
		.map(res=>{
			var us=res.json();
			us.forEach(item=>{
				if(item._id) item.id=item._id;
			})
			console.log(us);
			return us;
		});
	}
	deleteUser(id:string):Observable<User>{
		return this.http.delete(this.url+"/"+id)
		.map(res=>res.json());
	}
	addUser(name:string,age:number):Observable<User>{
		
		var user=new User(null,name,age);
		var body=JSON.stringify(user);
		
		var headers=new Headers({
			'Content-Type':'application/json'
		});
		var requestOptions=new RequestOptions({headers:headers});;
		return this.http.post(this.url,body,requestOptions)
		.map(res=>{
			var u=res.json();
			if(u._id) u.id=u._id;
			return u;
		});
	}
	updateUser(user:User):Observable<User>{
		var body=JSON.stringify(user);
		
		var headers=new Headers({
			'Content-Type':'application/json'
		});
		var requestOptions=new RequestOptions({headers:headers});
		return this.http.put(this.url+"/"+user.id,body,requestOptions)
		.map(res=>res.json());
	}
}






